package com.yanxu;

import java.beans.beancontext.BeanContext;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2025-05-29-2025
 * @Description: server 服务端
 */
public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = null;
        try {
            //启动 ServerSocket，监听 8888 端口
            serverSocket = new ServerSocket(9999);
            while (true) {
                // accept 等待客户端连接
                // accept 是阻塞函数，会一直在这里等待有客户端上线连接它!!!
                // 直到有客户端连接过来，才会继续往下走
                Socket socket = serverSocket.accept();
                String clientName = socket.getRemoteSocketAddress() + ":" + socket.getPort();
                System.out.println(clientName + " 上线了!!!");

                // 获取 reader、writer
                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

                // 死循环，不断读取客户端内容
                String msg = null;
                while ((msg = reader.readLine()) != null) {
                    // 输出客户端内容
                    System.out.println(clientName + ": " + msg);

                    // 回写客户端消息
                    writer.write("服务端：" + msg + "\n");
                    writer.flush();

                    if ("bye".equals(msg)) {
                        System.out.println(clientName + " 要退出了!!!");
                        break;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            serverSocket.close();
        }
    }
}